<?php

namespace app\common\model;

use app\beautiful\model\PrinterModel;
use app\common\model\account\ShopAccountModel;
use think\facade\Db;


class SupplierModel extends CommonModel{

    protected  $name = 'beautiful_supplier';

    protected  $pk   = 'id';


    public static function info($where){
        $info = Db::name('beautiful_supplier')->alias('a')
            ->where(['a.is_delete'=>0])
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['a.shop_id'=>$where['shop_id']]);
            })
            ->when(!empty($where['id']),function ($query) use ($where){
                $query->where(['a.id'=>$where['id']]);
            })
            ->when(isset($where['is_effect']),function ($query) use ($where){
                $query->where(['a.is_effect'=>$where['is_effect']]);
            })
            ->when(!empty($where['name']),function ($query) use ($where){
                $query->where('a.name','like','%'.$where['name'].'%');
            })
            ->field("a.*")
            ->find();
        if(!empty($info)){
            $info['images']=json_decode($info['images'],true);
        }
        return $info;
    }
    public static function list($where,$order=['a.id'=>'desc'],$page=1,$limit=10){
        $query = Db::name('beautiful_supplier')->alias('a')
            ->where(['a.is_delete'=>0])
            ->when(!empty($where['shop_id']),function ($query) use ($where){
                $query->where(['a.shop_id'=>$where['shop_id']]);
            })
            ->when(isset($where['is_effect']),function ($query) use ($where){
                $query->where(['a.is_effect'=>$where['is_effect']]);
            })
            ->when(!empty($where['name']),function ($query) use ($where){
                $query->where('a.name','like','%'.$where['name'].'%');
            })
            ->field("a.*");
        $count=$query->count();
        $list=$query->order($order)
            ->limit($limit)->page($page)
            ->select()
            ->toArray();
        if(!empty($list)){
            foreach ($list as &$v){
                $where=[];
                $where['supplier_id']=$v['id'];
                $v['goods_list'] = SupplierGoodsModel::list($where);
                if(empty(json_decode($v['images'],true))){
                    $v['images']=[];
                }else{
                    $v['images']=json_decode($v['images'],true);
                }
            }
        }
        return compact('count','list');
    }
    public static function up($data,$where){
        $data['edit_time']=date('Y-m-d H:i:s');
        $res=self::update($data,$where);
        return $res;
    }
    public static function getById($where,$field='*')
    {
        $list = Db::name('beautiful_supplier')->where($where)->field($field)->find();

        return $list;
    }
}

